/////////////////////////////////////////////////////////////////////
//
//  Tackle - A Scrum Tracking Web Site Solution
//  Released under Microsoft Permissive License (Ms-PL)
//  http://www.codeplex.com/Tackle/Project/License.aspx
//
/////////////////////////////////////////////////////////////////////

//
// Original Source from 
// http://tuldoklambat.blogspot.com/2005/11/viewstate-compression-and-_113274519039560470.html
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.IO;

public class ZipPage : System.Web.UI.Page
{

    protected override void OnPreLoad(EventArgs e)
    {
        this.Session["_storeViewStateInServer"] = false;
        base.OnPreLoad(e);
    }

    public bool StoreViewStateInServer
    {
        get
        {
            return (bool)this.Session["_storeViewStateInServer"];
        }
        set
        {
            this.Session["_storeViewStateInServer"] = value;
        }
    }

    protected override object LoadPageStateFromPersistenceMedium()
    {
        LosFormatter f = new LosFormatter();
        string vstate = String.Empty;
        if (StoreViewStateInServer)
        {
            string fn = GetFileName();
            if (File.Exists(fn))
            {
                StreamReader sr = new StreamReader(GetFileName());
                vstate = sr.ReadToEnd();
                sr.Close();
            }
            else
                return null;
        }
        else
        {
            vstate = this.Request.Form["__ZIPSTATE"];
            byte[] b = Convert.FromBase64String(vstate);
            b = Deflate.Decompress(b);
            vstate = Convert.ToBase64String(b);
        }

        return f.Deserialize(vstate);
    }

    protected override void SavePageStateToPersistenceMedium(object state)
    {
        LosFormatter f = new LosFormatter();
        if (StoreViewStateInServer)
        {
            StreamWriter sw = new StreamWriter(GetFileName());
            f.Serialize(sw, state);
            sw.Close();
        }
        else
        {
            StringWriter sw = new StringWriter();
            f.Serialize(sw, state);
            byte[] b = Convert.FromBase64String(sw.ToString());
            b = Deflate.Compress(b);
            ClientScript.RegisterHiddenField("__ZIPSTATE", Convert.ToBase64String(b));
        }
    }

    private string GetFileName()
    {
        string url = Request.ServerVariables["Path_Info"];
        url = url.Replace("/", "_");

        // Place the file in a temp folder (with write permissions) 
        string fileName = "viewstate/MasterBacklog_{0}.viewstate";
        fileName = String.Format(fileName, Session.SessionID);
        return Server.MapPath(fileName);
    }

}

